package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-05-22
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {


    @Override
    public R<Page> pageQuery(Integer page, Integer pageSize) {
        Page<Category> categoryPage = new Page<>(page,pageSize);
        categoryPage.addOrder(new OrderItem("sort",true));
        //执行分页查询
        Page<Category> p = page(categoryPage);
        return R.success(p);
    }

    @Override
    public void remove(Long id) {
        //.根据分类id查询关联的菜品表是否有数据
        Long count1 = Db.lambdaQuery(Dish.class).eq(Dish::getCategoryId, id).count();

        if(count1>0){
            throw new CustomException("该类与菜品表有关联,无法删除");
        }

        //根据分类id查询关联的套餐表是否有数据

        Long count2 = Db.lambdaQuery(Setmeal.class).eq(Setmeal::getCategoryId, id).count();

        if(count1>0){
            throw new CustomException("该类与套餐表有关联,无法删除");
        }

        removeById(id);
    }

    @Override
    public R<List<Category>> getCategoryByType(Category category) {
        List<Category> categories = lambdaQuery()
                .eq(category.getType()!=null,Category::getType, category.getType())
                .orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime)
                .list();

        return R.success(categories);
    }
}
